package org.goyo.main.web.controller.base;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.goyo.common.baseBean.AjaxResult;
import org.goyo.common.baseBean.Constants;
import org.goyo.common.excel.ExcelUtil;
import org.goyo.common.exception.DBException;
import org.goyo.common.exception.ServiceException;
import org.goyo.common.utils.JSONUtil;
import org.goyo.common.utils.Pager;
import org.goyo.common.utils.ToolUtils;
import org.goyo.main.domain.entity.BaseObject;
import org.goyo.main.domain.entity.base.Customer;
import org.goyo.main.domain.entity.system.SysUser;
import org.goyo.main.domain.excelBean.CustomerExcel;
import org.goyo.main.domain.excelBean.MaterialExcel;
import org.goyo.main.services.base.ICustomerService;
import org.goyo.main.services.log.MethodLog;
import org.goyo.main.web.controller.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 客户
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/customer")
public class CustomerController extends BaseController {
  protected Logger logger = LoggerFactory.getLogger(this.getClass());

  @Resource
  private ICustomerService customerService;

  /**
   * 列表界面
   * 
   * @author chenchuan 2014年11月9日
   */
  @RequestMapping("/toCustomerList")
  public String toCustomerList(HttpServletRequest request) {
    logger.info("----------------------");
    return "/base/CustomerList";
  }

  /**
   * 保存或者更新
   * 
   * @author chenchuan 2014年11月9日
   */
  @MethodLog("保存或者修改客户")
  @RequestMapping("/saveOrUpdateCustomer")
  @ResponseBody
  public AjaxResult saveOrUpdateCustomer(HttpServletRequest request) {
    AjaxResult result = null;
    try {
      Map pm = request.getParameterMap();
      String customer = request.getParameter("customer");
      Customer customerBean = JSONUtil.json2Obj(customer, Customer.class);
      BaseObject obj = customerService.saveOrUpdateInfo(customerBean);
      result = AjaxResult.resultSuccess("保存成功", obj);
    } catch (DBException | ServiceException e) {
      result = AjaxResult.resultFail("保存失败", null);
      logger.error(e.getMessage(), e);
    }
    return result;
  }

  /**
   * 提交数据
   * 
   * @author chenchuan 2014年11月16日
   */
  @RequestMapping("/submitCustomer")
  @ResponseBody
  public AjaxResult submitCustomer(HttpServletRequest request) {
    AjaxResult result = null;
    Object[] uuids = null;

    String rows = request.getParameter("rows");
    try {
      if (rows != null && !"".equals(rows)) {
        JSONArray jsonarray = JSONArray.fromObject(rows);
        List<Customer> list = (List<Customer>) JSONArray.toCollection(jsonarray, Customer.class);
        uuids = ToolUtils.getFiles(list, "uuid").toArray();
      } else {
        String uuid = request.getParameter("uuid");
        uuids = new Object[] {uuid};
      }
      BaseObject obj = customerService.submitInfo(uuids);
      result = AjaxResult.resultSuccess("提交成功", obj);
    } catch (Exception e) {
      result = AjaxResult.resultFail("提交失败", null);
      logger.error(e.getMessage(), e);
    }
    return result;
  }

  /**
   * 审核数据
   * 
   * @author chenchuan 2014年11月16日
   */
  @RequestMapping("/auditCustomer")
  @ResponseBody
  public AjaxResult auditCustomer(HttpServletRequest request) {
    AjaxResult result = null;
    Object[] uuids = null;

    String rows = request.getParameter("rows");
    try {
      if (rows != null && !"".equals(rows)) {
        JSONArray jsonarray = JSONArray.fromObject(rows);
        List<Customer> list = (List<Customer>) JSONArray.toCollection(jsonarray, Customer.class);
        uuids = ToolUtils.getFiles(list, "uuid").toArray();
      } else {
        String uuid = request.getParameter("uuid");
        uuids = new Object[] {uuid};
      }
      BaseObject obj = customerService.auditInfo(uuids);
      result = AjaxResult.resultSuccess("审核成功", obj);
    } catch (Exception e) {
      result = AjaxResult.resultFail("审核失败", null);
      logger.error(e.getMessage(),e);
    }
    return result;
  }

  /**
   * 反审核数据
   * 
   * @author chenchuan 2014年11月16日
   */
  @RequestMapping("/unAuditCustomer")
  @ResponseBody
  public AjaxResult unAuditCustomer(HttpServletRequest request) {
    AjaxResult result = null;
    Object[] uuids = null;

    String rows = request.getParameter("rows");
    try {
      if (rows != null && !"".equals(rows)) {
        JSONArray jsonarray = JSONArray.fromObject(rows);
        List<Customer> list = (List<Customer>) JSONArray.toCollection(jsonarray, Customer.class);
        uuids = ToolUtils.getFiles(list, "uuid").toArray();
      } else {
        String uuid = request.getParameter("uuid");
        uuids = new Object[] {uuid};
      }
      BaseObject obj = customerService.unAuditInfo(uuids);
      result = AjaxResult.resultSuccess("反审核成功", obj);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
    return result;
  }

  /**
   * 删除
   * 
   * @author chenchuan 2014年11月9日
   */
  @MethodLog("删除客户信息")
  @RequestMapping("/delCustomer")
  @ResponseBody
  public AjaxResult delCustomer(HttpServletRequest request) {
    AjaxResult result = null;
    try {
      String rows = request.getParameter("rows");
      JSONArray jsonarray = JSONArray.fromObject(rows);
      List<Customer> list = (List<Customer>) JSONArray.toCollection(jsonarray, Customer.class);
      customerService.delByUuids(ToolUtils.getFiles(list, "uuid").toArray());
      result = AjaxResult.resultSuccess("删除成功", null);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
    return result;
  }

  /**
   * 查看
   * 
   * @author chenchuan 2014年11月9日
   */
  @MethodLog("查看客户")
  @RequestMapping("/viewCustomer")
  public String viewCustomer(HttpServletRequest request, Model model) {
    String uuid = request.getParameter("uuid");
    Customer info = null;
    try {
      info = customerService.findByUuid(uuid);
    } catch (Exception e) {
      logger.error(e.getMessage(),e);
    }
    model.addAttribute("info", JSONUtil.obj2Json(info));
    model.addAttribute("status", Constants.VIEW);
    return "/base/CustomerEdit";
  }

  /**
   * 修改
   * 
   * @author chenchuan 2014年11月9日
   */
  @MethodLog("修改客户信息")
  @RequestMapping("/alterCustomer")
  public String alterCustomer(HttpServletRequest request, Model model) {
    String uuid = request.getParameter("uuid");
    Customer info = null;
    try {
      info = customerService.findByUuid(uuid);
    } catch (Exception e) {
        logger.error(e.getMessage(),e);
    }
    model.addAttribute("info", JSONUtil.obj2Json(info));
    model.addAttribute("status", Constants.EDIT);
    return "/base/CustomerEdit";
  }

  /**
   * 添加
   * 
   * @author chenchuan 2014年11月9日
   */
  @MethodLog("新增客户")
  @RequestMapping("/addCustomer")
  public String addCustomer(HttpServletRequest request, Model model) {
    model.addAttribute("status", Constants.NEW);
    model.addAttribute("number",getBaseNumber(Customer.BIZTYPE));
    model.addAttribute("customerProperUuid",request.getParameter("customerProperUuid"));
    return "/base/CustomerEdit";
  }

  /**
   * list列表数据加载
   * 
   * @author chenchuan 2014年11月9日
   */
  @MethodLog("查询客户信息")
  @RequestMapping("/listData")
  @ResponseBody
  public String ListData(HttpServletRequest request, Model model) {
    JSONObject data = null;
    // 获取条件
    // Map<String, Object> cond = JSONUtil.json2Map(request.getParameter("cond"));
    // 分页条件
    int page = Integer.parseInt(request.getParameter("page"));
    int pageSize = Integer.parseInt(request.getParameter("pagesize"));
    String sortname = request.getParameter("sortname");
    String sortorder = request.getParameter("sortorder");
    String rigidCondition = request.getParameter("rigidCondition");
    String where = request.getParameter("where");
  //左边树的id
    if(!StringUtils.isEmpty(rigidCondition)){
      if(where != null && !"".equals(where)){
        where = where + " and "+rigidCondition+" ";
      }else{
          where = rigidCondition;
      }
    }
    // 分页器
    Pager pager = Pager.convert(page, pageSize, sortname, sortorder);
    try {
      pager = customerService.findByCondition(where, pager);
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("Rows", pager.getList());
      map.put("Total", pager.getCount());
      data = JSONObject.fromObject(map);
    } catch (Exception e) {
        logger.error(e.getMessage(),e);
    }
    return data.toString();
  }
  
  
  @RequestMapping("/checkNumberUsed")
  public void checkNumberUsed(HttpServletRequest request, HttpServletResponse response) throws IOException{
    String uuid = request.getParameter("uuid");
    String number = request.getParameter("number");
    response.reset();
    response.setContentType("text/html;charset=UTF-8");
   //业务逻辑操作countByParams得到值并存储到num中
    SysUser sysuser = null;
    try {
      if(StringUtils.isEmpty(number)){
        response.getWriter().print(false);  
      }else{
        if(customerService.checkNumberUsed(uuid,number)){
          response.getWriter().print(false);  
        }else{
          response.getWriter().print(true);  
        }
      }
    } catch (Exception e) {
      response.getWriter().print(false);
      logger.error(e.getMessage(),e);
    }
  }
  
  
  @MethodLog("导入商品excle")
  @RequestMapping("/importCustomerExcel")
  @ResponseBody
  public AjaxResult importCustomerExcel(HttpServletRequest request,HttpServletResponse response){
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile files = multipartRequest.getFile("file");
    if(files.getSize()!=0){
        try {
            Map<Object,Object> result = ExcelUtil.ExcelImportToObjec(CustomerExcel.class, ExcelUtil.getBytes(files.getInputStream()),false);
            if(null!=result){
                if(result.get(true)!=null){
                    List<CustomerExcel> list = (List<CustomerExcel>) result.get(true);
                    if(null!=list&&null!=list.get(0)){
                    	customerService.saveOrUpdateCustomerList(list);
                    }else{
                        return  AjaxResult.resultFail("数据不完整，请检查后导入！",null);
                    }
                    int validData = list.size();
                    return AjaxResult.resultSuccess("导入成功，共保存"+validData+"条数据！",null);
                }else if(result.get(false)!=null){
                    return AjaxResult.resultFail((String)result.get(false),null);
                }else{
                    return AjaxResult.resultFail("发生错误，导入失败！",null);
                }
            }else{
                return AjaxResult.resultFail("可转换内容为空，导入失败！",null);
            }
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
            return AjaxResult.resultFail("发生错误，导入失败！",null);
        }
    }else{
        return AjaxResult.resultFail("文件大小为零，导入失败！",null);
    }
  }
}
